const RoomKeeper = require('../utils/RoomKeeper')
const { ChatMessage, AttentionMsg } = require('../utils/Message')

// ws消息类型
const WS_MTYPES = {
    'CHAT_MSG': 'chat-message', // 聊天消息
    'MODIFY_UINFO': 'modify-uinfo', // 修改链接信息
    'ATTENTION_MSG': 'attention-message'
}

class WsController {
    [WS_MTYPES.CHAT_MSG](connection, data) {
        console.log('controller', data)
        const from = RoomKeeper.rooms['/'].list.get(connection).name
        // 向房间内所有用户发送
        RoomKeeper.rooms['/'].list.forEach((info, con) => {
            con.send(ChatMessage(data.data, from))
        })
    }
    [WS_MTYPES.MODIFY_UINFO](connection, data) {
        console.log('data')
        RoomKeeper.rooms['/'].list.set(connection, { name: data.data.name })
        // 返回一个成功消息
        connection.send(AttentionMsg('modify-uinfo-succ', {
            text: '修改成功',
            data: data.data.name
        }))
    }
}

const controller = new WsController

function formatter(connection, message) {
    console.log('message', message)
    try {
        // 我觉得你是个object
        message = JSON.parse(message)
        const strategy = controller[message.type]

        console.log(message.type, strategy)

        strategy(connection, message)

    } catch (e) {
        console.log(e)
        // 不管了先
    }
}

module.exports = formatter